package com.windward.vii.service;

import com.windward.vii.common.JsonResult;
import com.windward.vii.dao.entity.Statistics;
import com.windward.vii.dao.mapper.StatisticsMapper;
import com.windward.vii.utils.StringUtils;
import com.windward.vii.utils.ThreadPoolManager;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class StatisticsService {

    @Resource
    StatisticsMapper statisticsMapper;

    public JsonResult smsStatistics(String url) {
        asyncIncreaseCountByUrl(url);
        return JsonResult.success();
    }

    private void asyncIncreaseCountByUrl(final String url) {
        ThreadPoolManager.getInstance().addExecuteTask(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!StringUtils.isBlank(url)) {
                        int row = statisticsMapper.increaseCountByUrl(url.trim());
                        if(row < 1) {
                            Statistics statistics = new Statistics();
                            statistics.setUrl(url);
                            statistics.setCount(1L);
                            statisticsMapper.insertSelective(statistics);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
